import PropTypes from 'prop-types';
import RcTabs, { TabPane } from 'rc-tabs';
import ScrollableInkTabBar from 'rc-tabs/lib/ScrollableInkTabBar';
import TabContent from 'rc-tabs/lib/TabContent';
import React from 'react';
import ReactDOM from 'react-dom';

export interface ITabsProps {
  /**
   * tab切换后回调
   */
  onChange?: (key: string) => void;
  activeKey?: string;
  /**
   * 如果 activeKey 不存在时，使用defaultActiveKey
   */
  defaultActiveKey?: string;
  children?: React.ReactNode;
}

const Pane = TabPane;

export class Tabs extends React.Component<ITabsProps> {
  public static propTypes = {
    onChange: PropTypes.func,
    activeKey: PropTypes.string,
    defaultActiveKey: PropTypes.string,
    children: PropTypes.node,
  };
  public static Pane = Pane;

  public componentDidMount() {
    this.updateUnderline();
  }

  public componentDidUpdate() {
    this.updateUnderline();
  }

  public updateUnderline() {
    // Tabs组件自身所在DOM节点
    const currentEle = ReactDOM.findDOMNode(this) as HTMLElement;
    if (currentEle) {
      const underline = currentEle.getElementsByClassName('rc-tabs-ink-bar')[0];
      if (underline) {
        currentEle.appendChild(underline);
      }
    }
  }

  public render() {
    return (
      <RcTabs
        {...this.props}
        renderTabBar={() => <ScrollableInkTabBar />}
        renderTabContent={() => <TabContent />}
      >
        {this.props.children}
      </RcTabs>
    );
  }
}
